// 仓库管理工具函数

/**
 * 格式化数量显示
 * @param {number} quantity - 数量
 * @param {string} unit - 单位
 * @param {number} decimals - 小数位数
 * @returns {string} 格式化后的数量
 */
export function formatQuantity(quantity, unit = '', decimals = 2) {
  if (quantity === null || quantity === undefined) return '0'
  
  const num = parseFloat(quantity)
  if (isNaN(num)) return '0'
  
  const formatted = num.toFixed(decimals)
  return unit ? `${formatted} ${unit}` : formatted
}

/**
 * 格式化金额显示
 * @param {number} amount - 金额
 * @param {string} currency - 货币符号
 * @param {number} decimals - 小数位数
 * @returns {string} 格式化后的金额
 */
export function formatAmount(amount, currency = '¥', decimals = 2) {
  if (amount === null || amount === undefined) return `${currency}0.00`
  
  const num = parseFloat(amount)
  if (isNaN(num)) return `${currency}0.00`
  
  return `${currency}${num.toFixed(decimals)}`
}

/**
 * 格式化日期时间
 * @param {string|Date} date - 日期
 * @param {string} format - 格式
 * @returns {string} 格式化后的日期
 */
export function formatDateTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return ''
  
  const d = new Date(date)
  if (isNaN(d.getTime())) return ''
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 格式化日期
 * @param {string|Date} date - 日期
 * @returns {string} 格式化后的日期
 */
export function formatDate(date) {
  return formatDateTime(date, 'YYYY-MM-DD')
}

/**
 * 获取状态标签和颜色
 * @param {string} status - 状态值
 * @returns {object} 状态信息
 */
export function getStatusInfo(status) {
  const statusMap = {
    pending: { text: '待提交', color: '#ff9800', type: 'warning' },
    submitted: { text: '已提交', color: '#2196f3', type: 'info' },
    approved: { text: '已审批', color: '#4caf50', type: 'success' },
    rejected: { text: '已拒绝', color: '#f44336', type: 'error' },
    cancelled: { text: '已取消', color: '#9e9e9e', type: 'default' },
    completed: { text: '已完成', color: '#4caf50', type: 'success' },
    draft: { text: '草稿', color: '#9e9e9e', type: 'default' }
  }
  
  return statusMap[status] || { text: status, color: '#9e9e9e', type: 'default' }
}

/**
 * 获取仓库类型信息
 * @param {string} type - 仓库类型
 * @returns {object} 仓库类型信息
 */
export function getWarehouseTypeInfo(type) {
  const typeMap = {
    raw_material: { text: '原辅料', color: '#ff9800' },
    hardware: { text: '五金', color: '#2196f3' },
    spare_parts: { text: '备件', color: '#4caf50' },
    finished_goods: { text: '成品', color: '#9c27b0' },
    work_in_progress: { text: '在制品', color: '#607d8b' }
  }
  
  return typeMap[type] || { text: type, color: '#9e9e9e' }
}

/**
 * 验证批号格式
 * @param {string} batchNo - 批号
 * @returns {boolean} 是否有效
 */
export function validateBatchNo(batchNo) {
  if (!batchNo || typeof batchNo !== 'string') return false
  
  // 批号格式：字母数字组合，长度6-20位
  const pattern = /^[A-Za-z0-9]{6,20}$/
  return pattern.test(batchNo.trim())
}

/**
 * 验证重量数据
 * @param {string|number} weight - 重量
 * @returns {object} 验证结果
 */
export function validateWeight(weight) {
  if (weight === null || weight === undefined || weight === '') {
    return { valid: false, message: '重量不能为空' }
  }
  
  const num = parseFloat(weight)
  if (isNaN(num)) {
    return { valid: false, message: '重量必须是数字' }
  }
  
  if (num <= 0) {
    return { valid: false, message: '重量必须大于0' }
  }
  
  if (num > 100000) {
    return { valid: false, message: '重量超出合理范围' }
  }
  
  return { valid: true, value: num }
}

/**
 * 解析扫码数据
 * @param {string} scanResult - 扫码结果
 * @returns {object} 解析结果
 */
export function parseScanData(scanResult) {
  if (!scanResult || typeof scanResult !== 'string') {
    return { success: false, message: '无效的扫码结果' }
  }
  
  const result = scanResult.trim()
  
  // 批号扫码格式：BATCH:XXXXXX
  if (result.startsWith('BATCH:')) {
    const batchNo = result.substring(6)
    if (validateBatchNo(batchNo)) {
      return {
        success: true,
        type: 'batch',
        data: { batchNo }
      }
    }
    return { success: false, message: '批号格式无效' }
  }
  
  // 重量扫码格式：WEIGHT:XXXX
  if (result.startsWith('WEIGHT:')) {
    const weight = result.substring(7)
    const validation = validateWeight(weight)
    if (validation.valid) {
      return {
        success: true,
        type: 'weight',
        data: { weight: validation.value }
      }
    }
    return { success: false, message: validation.message }
  }
  
  // 物料码格式：MATERIAL:XXXX
  if (result.startsWith('MATERIAL:')) {
    const materialCode = result.substring(9)
    return {
      success: true,
      type: 'material',
      data: { materialCode }
    }
  }
  
  // 合同码格式：CONTRACT:XXXX
  if (result.startsWith('CONTRACT:')) {
    const contractCode = result.substring(9)
    return {
      success: true,
      type: 'contract',
      data: { contractCode }
    }
  }
  
  // 库位码格式：LOCATION:XXXX
  if (result.startsWith('LOCATION:')) {
    const locationCode = result.substring(9)
    return {
      success: true,
      type: 'location',
      data: { locationCode }
    }
  }
  
  // 出库单码格式：OUTBOUND:XXXX
  if (result.startsWith('OUTBOUND:')) {
    const outboundCode = result.substring(9)
    return {
      success: true,
      type: 'outbound',
      data: { outboundCode }
    }
  }
  
  return { success: false, message: '无法识别的扫码格式' }
}

/**
 * 验证出库数量
 * @param {number} quantity - 出库数量
 * @param {number} availableStock - 可用库存
 * @param {number} minQuantity - 最小出库数量
 * @param {number} maxQuantity - 最大出库数量
 * @returns {object} 验证结果
 */
export function validateOutboundQuantity(quantity, availableStock, minQuantity = 0, maxQuantity = Infinity) {
  if (quantity === null || quantity === undefined || quantity === '') {
    return { valid: false, message: '出库数量不能为空' }
  }
  
  const num = parseFloat(quantity)
  if (isNaN(num)) {
    return { valid: false, message: '出库数量必须是数字' }
  }
  
  if (num <= minQuantity) {
    return { valid: false, message: `出库数量必须大于${minQuantity}` }
  }
  
  if (num > availableStock) {
    return { valid: false, message: '出库数量不能大于可用库存' }
  }
  
  if (num > maxQuantity) {
    return { valid: false, message: `出库数量不能超过${maxQuantity}` }
  }
  
  return { valid: true, value: num }
}

/**
 * 获取出库类型信息
 * @param {string} type - 出库类型
 * @returns {object} 出库类型信息
 */
export function getOutboundTypeInfo(type) {
  const typeMap = {
    sales: { text: '销售出库', color: '#4caf50', icon: 'shop' },
    production: { text: '生产出库', color: '#2196f3', icon: 'factory' },
    transfer: { text: '调拨出库', color: '#ff9800', icon: 'exchange' },
    return: { text: '退货出库', color: '#f44336', icon: 'return' },
    scrap: { text: '报废出库', color: '#9c27b0', icon: 'delete' },
    other: { text: '其他出库', color: '#607d8b', icon: 'more' }
  }
  
  return typeMap[type] || { text: type, color: '#9e9e9e', icon: 'help' }
}

/**
 * 构建出库提交数据
 * @param {object} formData - 表单数据
 * @param {array} materials - 物料列表
 * @param {string} type - 出库类型
 * @returns {object} 提交数据
 */
export function buildOutboundSubmitData(formData, materials, type) {
  const baseData = {
    type,
    warehouseId: formData.warehouseId,
    processId: formData.processId,
    outboundDate: formData.outboundDate,
    remark: formData.remark || '',
    materials: materials.map(item => ({
      materialId: item.materialId,
      materialCode: item.materialCode,
      materialName: item.materialName,
      specification: item.specification,
      unit: item.unit,
      quantity: item.quantity,
      batchNo: item.batchNo,
      locationCode: item.locationCode,
      unitPrice: item.unitPrice || 0,
      totalAmount: (item.unitPrice || 0) * item.quantity
    })),
    totalQuantity: materials.reduce((sum, item) => sum + item.quantity, 0),
    totalAmount: materials.reduce((sum, item) => sum + (item.unitPrice || 0) * item.quantity, 0)
  }
  
  // 根据出库类型添加特定字段
  switch (type) {
    case 'sales':
      return {
        ...baseData,
        customerId: formData.customerId,
        customerName: formData.customerName,
        salesOrderNo: formData.salesOrderNo
      }
    case 'production':
      return {
        ...baseData,
        workOrderNo: formData.workOrderNo,
        productionLine: formData.productionLine
      }
    case 'transfer':
      return {
        ...baseData,
        targetWarehouseId: formData.targetWarehouseId,
        targetWarehouseName: formData.targetWarehouseName,
        transferNo: formData.transferNo
      }
    default:
      return baseData
  }
}

/**
 * 计算金额
 * @param {number} quantity - 数量
 * @param {number} price - 单价
 * @param {number} taxRate - 税率
 * @returns {object} 计算结果
 */
export function calculateAmount(quantity, price, taxRate = 0) {
  const qty = parseFloat(quantity) || 0
  const prc = parseFloat(price) || 0
  const tax = parseFloat(taxRate) || 0
  
  const amount = qty * prc
  const taxAmount = amount * tax
  const totalAmount = amount + taxAmount
  
  return {
    amount: Math.round(amount * 100) / 100,
    taxAmount: Math.round(taxAmount * 100) / 100,
    totalAmount: Math.round(totalAmount * 100) / 100
  }
}

/**
 * 生成入库单号
 * @param {string} warehouseCode - 仓库代码
 * @returns {string} 入库单号
 */
export function generateStockInNo(warehouseCode) {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const time = String(date.getTime()).slice(-6)
  
  return `IN${warehouseCode}${year}${month}${day}${time}`
}

/**
 * 生成批号
 * @param {string} materialCode - 物料代码
 * @param {string} supplierCode - 供应商代码
 * @returns {string} 批号
 */
export function generateBatchNo(materialCode, supplierCode) {
  const date = new Date()
  const year = date.getFullYear().toString().slice(-2)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.random().toString(36).substring(2, 5).toUpperCase()
  
  return `${materialCode}${supplierCode}${year}${month}${day}${random}`
}

/**
 * 深拷贝对象
 * @param {object} obj - 要拷贝的对象
 * @returns {object} 拷贝后的对象
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(deepClone)
  
  const cloned = {}
  Object.keys(obj).forEach(key => {
    cloned[key] = deepClone(obj[key])
  })
  
  return cloned
}

/**
 * 防抖函数
 * @param {function} func - 要执行的函数
 * @param {number} wait - 等待时间（毫秒）
 * @returns {function} 防抖后的函数
 */
export function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 * @param {function} func - 要执行的函数
 * @param {number} limit - 限制时间（毫秒）
 * @returns {function} 节流后的函数
 */
export function throttle(func, limit) {
  let inThrottle
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}